package database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DatabaseManager 
{
    //Load driver for database
  	private static boolean loadDatabaseDriver()
  	{
  	  try 
  	  {
  	    Class.forName("com.mysql.jdbc.Driver");
  		return true;
  	  } 
  	  catch (ClassNotFoundException e)
  	  {
  		return false;
  	  }
  		
  	}

  	//Get connection to database
  	private static Connection connectToDatabase()
  	{
  	  Connection con = null;
  	  
  	  try 
  	  {
  	    con = DriverManager.getConnection("jdbc:mysql://localhost/" + "rsd","root","mwndb");
  	    return con;
  	  } 
  	  catch (SQLException e) 
  	  {
  		return null;
  	  }
  		
  	}
  	
  	//Get database driver and connect at once
  	public static Connection getDatabaseDriverAndConnect()
  	{
  	  if(loadDatabaseDriver())
  	    return connectToDatabase();
  	    
  	  return null;
  	}

    //Create Statement with query
  	public static Statement createQuery(Statement stmt, Connection con) throws SQLException
  	{
      try 
      {
        stmt = con.createStatement();
      } 
      catch (SQLException e) 
      {
        throw new SQLException();
      }	
    	  
      return stmt;
  	}
  
    //Execute query
	public static ResultSet executeQuery(ResultSet rs,Statement stmt, String query) throws SQLException
	{
	  try 
	  {
	    rs = stmt.executeQuery(query);
	  } 
	  catch (SQLException e) 
	  { 
	    throw new SQLException();
	  }
	  
	  return rs;
	}
	
	//Execute update
	public static int executeUpdate(Statement stmt, String query) throws SQLException
	{
	  int res = 0;
	  try 
	  {
	    res = stmt.executeUpdate(query);
	  } 
	  catch (SQLException e) 
	  {
	    throw new SQLException();
	  }
			
	  return res;
   }
}
